<?php

namespace app\api\controller;

use addons\epay\library\Service;

use app\api\model\hotel\HotelThirdOrder as HotelThirdOrderModel;
use app\api\model\hotel\HotelOrderInvoice;
use app\common\controller\Api;
use app\common\model\pay\Pay;
use app\common\model\pay\Pay as PayModel;
use app\common\model\pay\PayShare;

class Hotelorder extends Api
{

    protected $noNeedLogin = ['cancel','notify','ceshipay','ceshishare'];
    protected $noNeedRight = ['*'];

    //订单列表
    public function lists()
    {
        $model = new HotelThirdOrderModel();

        $data = [
            'user_id'=>$this->auth->id,
            'order_status'=>input('order_status','all'),
        ];

        $res = $model->getUserOrderList($data);
        $this->success('',$res);
    }

    //订单详情
    public function info()
    {
        $model = new HotelThirdOrderModel();
        $order_id = input('order_id',0);
        $res = $model->getUserOrderInfo($order_id,$this->auth->id);
        $this->success('',$res);
    }

    //取消订单
    public function cancel()
    {
        try {
            $model = new HotelThirdOrderModel();
            $order_id = input('order_id',0);
            $res = $model->orderCancel($order_id);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消成功',$res);
    }

    //线下支付
    public function offlinepay()
    {
        $order_no = input('order_no','');
        $pay_type = input('pay_type','offlinepay');
        $model = new HotelThirdOrderModel();

        $res = $model->notify($order_no,$pay_type);
        $this->success('提交成功',$res);
    }

    //支付
    public function pay()
    {
        $order_no = input('order_no','');
        $pay_type = input('pay_type','wechat');
        $order = HotelThirdOrderModel::get(['order_no'=>$order_no])        ;
        $user = \app\common\model\User::get($this->auth->id);

        if (!$order){
            $this->error('订单不存在');
        }
        if ($order->pay_status==1)$this->error('已支付');

        if ($pay_type=='wechat'){
            $pay_model = new PayShare();

            $res = $pay_model->orderpay($order_no);
        } else {
            if ($user->money<$order['pay_money']){
                $this->error('余额不足');
            }

            $model = new HotelThirdOrderModel();

            $res = $model->notify($order_no,'balance');
        }

        $this->success('',$res);
    }

    public function ceshishare()
    {
        try {
            $order_no = input('order_no','');
            $pay_model = new PayShare();

            $res = $pay_model->share($order_no);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('',$res);
    }

    //回调
    public function notify()
    {
        $data = input();
        \think\Log::record($data);
        $model = new HotelThirdOrderModel();
        $out_trade_no = $data['cusorderid'];
        $res = $model->notify($out_trade_no,'wechat',$data['trxid']);
        $this->success('',$res);
        /*$paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑

            $model = new HotelThirdOrderModel();

            $res = $model->notify($out_trade_no,$paytype);
        } catch (\Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }*/

    }


    //开票申请
    public function invoiceApply()
    {
        $model = new HotelOrderInvoice();

        $data = [
            'user_id'=>$this->auth->id,
            'invoice_titile_id'=>input('invoice_titile_id',0),
            'order_id'=>input('order_id',0)
        ];

        if (empty($data['invoice_titile_id'])&&empty($data['order_id'])){
            $this->error('缺少必填参数');
        }

        $info = HotelOrderInvoice::get($data);

        if ($info&&$info['status']==1){
            $order = HotelThirdOrderModel::get($data['order_id']);

            if ($order->is_invoice==1){
                $this->error('该订单已申请开票');
            }
        }

        if ($info){
            $res = $model->save($data,['id'=>$info['id']]);
        } else {
            $res = $model->save($data);
        }

        if ($res){
            HotelThirdOrderModel::where(['order_id'=>$data['order_id']])->update(['is_invoice'=>1]);
            $this->success('申请成功');
        } else {
            $this->error('申请失败');
        }
    }

    //开票记录
    public function invoiceApplyLists()
    {
        $list = HotelOrderInvoice::alias('oi')
            ->join('hotel_third_order ho','oi.order_id = ho.order_id')
            ->where(['oi.user_id'=>$this->auth->id])
            ->field('oi.*,ho.order_no')
            ->order('oi.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $this->success('',$list);
    }

    //开票详情
    public function invoiceApplyInfo()
    {
        $id = input('id',0);

        $info = HotelOrderInvoice::alias('oi')
            ->join('hotel_third_order ho','oi.order_id = ho.order_id')
            ->where(['oi.user_id'=>$this->auth->id,'oi.id'=>$id])
            ->field('oi.*,ho.order_no')
            ->find();
        $this->success('',$info);
    }
}